export function download(binaryId) {
  return RSocket.rs({
    route: `files.${ROUTE(binaryId)}`,
    binary: true,
  });
}

export function getMeta(binaryId) {
  return RSocket.rr({
    route: `files.${ROUTE(binaryId)}.meta`,
  });
}

export function upload({ binaryId, mimeType, filename, arrayBuffer }) {
  return RSocket.rc({
    route: 'files.upload',
    args: {
      binary: {
        binaryId,
        mimeType,
        filename,
      },
    },
    data: Buffer.from(arrayBuffer),
  });
}

export async function customRequest({ file, binaryId, mimeType, filename }) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onloadend = async () => {
      try {
        await upload({
          binaryId,
          mimeType: mimeType || filename.type,
          filename: filename || filename.filename,
          arrayBuffer: reader.result,
        });
        resolve(file);
      } catch (e) {
        reject(e);
      }
    };
    reader.readAsArrayBuffer(file);
  });
}
